package com.fhhst.prodroid;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView mTitleTextView;
	private TextView mDumpTextView;
	private ScrollView mScrollView;
	private Button btnReset;
	private Button btnConnect;
	private final String TAG = "prodroid";

	/**
	 * The device currently in use, or {@code null}.
	 */
	private UsbSerialDriver mSerialDevice;

	/**
	 * The system's USB service.
	 */
	private UsbManager mUsbManager;

	private final ExecutorService mExecutor = Executors
			.newSingleThreadExecutor();

	private SerialInputOutputManager mSerialIoManager;

	private final SerialInputOutputManager.Listener mListener = new SerialInputOutputManager.Listener() {

		@Override
		public void onRunError(Exception e) {
			Log.d(TAG, "Runner stopped.");
		}

		@Override
		public void onNewData(final byte[] data) {
			MainActivity.this.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					MainActivity.this.updateReceivedData(data);
				}
			});
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

		mTitleTextView = (TextView) findViewById(R.id.demoTitle);
		mDumpTextView = (TextView) findViewById(R.id.demoText);
		mScrollView = (ScrollView) findViewById(R.id.demoScroller);
		btnReset = (Button) findViewById(R.id.btnReset);
		btnConnect = (Button) findViewById(R.id.btnConnect);
		linkButtons();
	}

	/**
	 * Link button onClickHandler
	 */
	private void linkButtons() {
		btnConnect.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});	
		
		
		/**
		 * Reset Button sets and clears the DTR (Data Terminal Ready) bit 
		 * in order to reset the printer and 
		 */
		btnReset.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					mSerialDevice.setDTR(true);

					mSerialDevice.setDTR(false);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		stopIoManager();
		if (mSerialDevice != null) {
			try {
				mSerialDevice.close();
			} catch (IOException e) {
				// Ignore.
			}
			mSerialDevice = null;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		mSerialDevice = UsbSerialProber.acquire(mUsbManager);

		Log.d(TAG, "Resumed, mSerialDevice=" + mSerialDevice);
		if (mSerialDevice == null) {
			mTitleTextView.setText("No serial device.");
		} else {
			try {
				mSerialDevice.setParameters(115200, 8, 1, 0);// parameter for
																// megaadk
				mSerialDevice.open();

			} catch (IOException e) {
				Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
				mTitleTextView.setText("Error opening device: "
						+ e.getMessage());
				try {
					mSerialDevice.close();
				} catch (IOException e2) {
					// Ignore.
				}
				mSerialDevice = null;
				return;
			}
			mTitleTextView.setText("Serial device: " + mSerialDevice);
		}
		onDeviceStateChange();
	}

	private void stopIoManager() {
		if (mSerialIoManager != null) {
			Log.i(TAG, "Stopping io manager ..");
			mSerialIoManager.stop();
			mSerialIoManager = null;
		}
	}

	private void startIoManager() {
		if (mSerialDevice != null) {
			Log.i(TAG, "Starting io manager ..");
			mSerialIoManager = new SerialInputOutputManager(mSerialDevice,
					mListener);
			mExecutor.submit(mSerialIoManager);
		}
	}

	private void onDeviceStateChange() {
		stopIoManager();
		startIoManager();
	}

	private void updateReceivedData(byte[] data) {
		// final String message = "Read " + data.length + " bytes: \n"
		// + HexDump.dumpHexString(data) + "\n\n";
		String str = null;
		try {
			str = new String(data, "UTF8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // for UTF8 encoding

		final String message = str;
		mDumpTextView.append(message);
		mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
	}

}
